﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace EcssTool.Logic
{
    public class ServiceDeliverHelper
    {
        /// <summary>
        /// 修正因BOSS响应超时导致的业务受理失败，并让订单正常完成。
        /// </summary>
        /// <param name="serviceId"></param>
        public string FixFailureService(string serviceId)
        {
            var finishedTime = Convert.ToDateTime("1900-1-1");
            UpdateServiceDetail(serviceId, out finishedTime);
            DeleteFailServiceDetail(serviceId);
            UpdateServiceStatus(serviceId, finishedTime);
            NotifyWCFService(GetOrderIdByServiceDeliverId(serviceId));

            return string.Format("修正业务受理[{0}]成功", serviceId);
        }

        /// <summary>
        /// 更改ServiceDeliverDetail表的超时记录状态为成功
        /// </summary>
        /// <param name="serviceId"></param>
        private void UpdateServiceDetail(string serviceId, out DateTime finishedTime)
        {
            var detialId = 0;
            finishedTime = Convert.ToDateTime("1900-1-1");

            var sql = @"select top 1 detailid,serviceDeliverTime from orderservciedeliverdetail where servicedeliverid=@servicedeliverid 
                        order by detailid";
            var sqlconn = new SqlConnection();
            var sqlcmd = new SqlCommand();

            sqlconn = new SqlConnection();
            sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["ECSSDb"].ConnectionString;

            sqlcmd = new SqlCommand();
            sqlcmd.CommandText = sql;
            sqlcmd.Connection = sqlconn;

            sqlcmd.Parameters.Add("@servicedeliverid", SqlDbType.Int);
            sqlcmd.Parameters["@servicedeliverid"].Value = Convert.ToInt32(serviceId);

            try
            {
                sqlcmd.Connection.Open();
                var sqlrd = sqlcmd.ExecuteReader();
                if (sqlrd.HasRows)
                {
                    sqlrd.Read();
                    detialId = (int)sqlrd["detailid"];
                    finishedTime = (DateTime)sqlrd["serviceDeliverTime"];
                }
            }
            finally
            {
                sqlcmd.Connection.Close();
            }

            if (detialId > 0)
            {
                sql = @"update orderservciedeliverdetail set deliverresult=1,deliverremark='系统自动受理成功' where detailid=@detailid";

                sqlconn = new SqlConnection();
                sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["ECSSDb"].ConnectionString;

                sqlcmd = new SqlCommand();
                sqlcmd.CommandText = sql;
                sqlcmd.Connection = sqlconn;

                sqlcmd.Parameters.Add("@detailid", SqlDbType.Int);
                sqlcmd.Parameters["@detailid"].Value = detialId;

                try
                {
                    sqlcmd.Connection.Open();
                    sqlcmd.ExecuteNonQuery();
                }
                finally
                {
                    sqlcmd.Connection.Close();
                }
            }
        }

        /// <summary>
        /// 删除ServiceDeliverDetail表的失败明细
        /// </summary>
        /// <param name="serviceId"></param>
        private void DeleteFailServiceDetail(string serviceId)
        {
            var sql = @"delete from orderservciedeliverdetail where serviceDeliverid=@serviceDeliverid and deliverresult=2";
            var sqlconn = new SqlConnection();
            var sqlcmd = new SqlCommand();

            sqlconn = new SqlConnection();
            sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["ECSSDb"].ConnectionString;

            sqlcmd = new SqlCommand();
            sqlcmd.CommandText = sql;
            sqlcmd.Connection = sqlconn;

            sqlcmd.Parameters.Add("@serviceDeliverid", SqlDbType.Int);
            sqlcmd.Parameters["@serviceDeliverid"].Value = Convert.ToInt32(serviceId);

            try
            {
                sqlcmd.Connection.Open();
                sqlcmd.ExecuteNonQuery();
            }
            finally
            {
                sqlcmd.Connection.Close();
            }
        }

        /// <summary>
        /// 更新ServiceDeliver表的状态及业务受理成功时间
        /// </summary>
        /// <param name="serviceId"></param>
        /// <param name="orderId"></param>
        private void UpdateServiceStatus(string serviceId, DateTime finishedTime)
        {
            var sql = @"update orderservicedeliver set disablestatus=0,status=1,remark=null,retrycount=null
                        where serviceDeliverid=@serviceDeliverid";
            var sqlconn = new SqlConnection();
            var sqlcmd = new SqlCommand();

            sqlconn = new SqlConnection();
            sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["ECSSDb"].ConnectionString;

            sqlcmd = new SqlCommand();
            sqlcmd.CommandText = sql;
            sqlcmd.Connection = sqlconn;

            sqlcmd.Parameters.Add("@serviceDeliverid", SqlDbType.Int);
            sqlcmd.Parameters["@serviceDeliverid"].Value = Convert.ToInt32(serviceId);

            try
            {
                sqlcmd.Connection.Open();
                sqlcmd.ExecuteNonQuery();
            }
            finally
            {
                sqlcmd.Connection.Close();
            }
        }

        /// <summary>
        /// 重新发起业务受理请求，以便订单走完
        /// </summary>
        /// <param name="orderId"></param>
        private void NotifyWCFService(string orderId)
        {
            var flag = false;
            var wcf = new OrderServiceDeliverWCF();
            try
            {
                wcf.OrderServiceDeliverNotify(orderId, null, out flag, out flag);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("调用WCF服务出错:{0}", ex.Message));
            }
        }

        /// <summary>
        /// 根据ServiceDeilverId获取OrderId
        /// </summary>
        /// <param name="serviceId"></param>
        /// <returns></returns>
        private string GetOrderIdByServiceDeliverId(string serviceId)
        {
            var sql = @"select orderid from orderservicedeliver where serviceDeliverid=@serviceDeliverid";
            var sqlconn = new SqlConnection();
            var sqlcmd = new SqlCommand();

            sqlconn = new SqlConnection();
            sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["ECSSDb"].ConnectionString;

            sqlcmd = new SqlCommand();
            sqlcmd.CommandText = sql;
            sqlcmd.Connection = sqlconn;

            sqlcmd.Parameters.Add("@serviceDeliverid", SqlDbType.Int);
            sqlcmd.Parameters["@serviceDeliverid"].Value = Convert.ToInt32(serviceId);

            try
            {
                sqlcmd.Connection.Open();
                var sqlrd = sqlcmd.ExecuteReader();
                if (sqlrd.HasRows)
                {
                    sqlrd.Read();
                    return sqlrd["orderid"].ToString();
                }
                else
                {
                    return null;
                }
            }
            finally
            {
                sqlcmd.Connection.Close();
            }
        }
    }
}
